package ru.minidoc.web;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class DBServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        try {
            Connection c = getDataSource().getConnection();
            c.close();
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    private DataSource getDataSource() {
        ServletContext context = getServletContext();
        WebApplicationContext applicationContext =
                WebApplicationContextUtils
                .getWebApplicationContext(context);

        DataSource ds = (DataSource) applicationContext.getBean("dataSource");
        return ds;
    }

    @Override
    public void destroy() {
        try {
            Connection c = getDataSource().getConnection();
            Statement statement = c.createStatement();
            statement.execute("SHUTDOWN");
            c.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
